package com.edu.hre.struts.action.pim;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmpEducation;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.pim.EmpEducationUpdateForm;

public class EmpEducationUpdateAction extends DispatchAction{
	
	private static final Logger logger = Logger.getLogger(EmpEducationUpdateAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "empEducationUpdate";
	
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());

		EmpEducationUpdateForm beanForm = (EmpEducationUpdateForm) form;
		beanForm.setIsAddNew(true);

		if(request.getParameter(StringConstants.BTN_ADD) == null){
			
			int empNum = CommonUtils.getIntParameter("emp_num", request);
			beanForm.setEmpNumber(empNum);

			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		EmployeeListAction.setAttributesForRequest(beanForm.getEmpNumber(), request);
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		Short year = Short.parseShort(beanForm.getYear());		
		Date startDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getStartDate()));
		Date endDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getEndDate()));
		
		HreEmpEducation tmp = new HreEmpEducation();
		tmp.setEmpNumber(beanForm.getEmpNumber());
		tmp.setEducationId(beanForm.getLevel());
		tmp.setInstitute(CommonUtils.normalizeString(beanForm.getInstitute()));
		tmp.setMajor(beanForm.getMajor());
		tmp.setYear(year);
		tmp.setScore(CommonUtils.normalizeString(beanForm.getScore()));
		tmp.setStartDate(startDate);
		tmp.setEndDate(endDate);
		tmp.setDateCreated(new Date());
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.INSERT_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		EmpEducationUpdateForm beanForm = (EmpEducationUpdateForm) form;
		beanForm.setIsAddNew(false);
		
		if(request.getParameter(StringConstants.BTN_EDIT) == null){
			
			int id = CommonUtils.getIntParameter("id", request);
			HreEmpEducation tmp = baseService.getFirstPojo("id", Compare.EQUAL, id, null, null, 0, HreEmpEducation.class);
			
			if (tmp == null) {
				beanForm.setMessage(StringConstants.BLANK);
				initFormBean(beanForm);
				return mapping.findForward(ACTION_NAME);
			}
			
			beanForm.setId(id);
			beanForm.setEmpNumber(tmp.getEmpNumber());
			beanForm.setLevel(tmp.getEducationId());
			beanForm.setInstitute(CommonUtils.normalizeString(tmp.getInstitute()));
			beanForm.setMajor(tmp.getMajor());
			beanForm.setYear(tmp.getYear() + StringConstants.BLANK);
			beanForm.setScore(CommonUtils.normalizeString(tmp.getScore()));
			beanForm.setStartDate(CommonUtils.dateToString(tmp.getStartDate()));
			beanForm.setEndDate(CommonUtils.dateToString(tmp.getEndDate()));

			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		EmployeeListAction.setAttributesForRequest(beanForm.getEmpNumber(), request);
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		Short year = Short.parseShort(beanForm.getYear());		
		Date startDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getStartDate()));
		Date endDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getEndDate()));

		HreEmpEducation tmp = baseService.getFirstPojo("id", Compare.EQUAL, beanForm.getId(), null, null, 0, HreEmpEducation.class);
		if (tmp == null) {
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		tmp.setEducationId(beanForm.getLevel());
		tmp.setInstitute(CommonUtils.normalizeString(beanForm.getInstitute()));
		tmp.setMajor(beanForm.getMajor());
		tmp.setYear(year);
		tmp.setScore(CommonUtils.normalizeString(beanForm.getScore()));
		tmp.setStartDate(startDate);
		tmp.setEndDate(endDate);
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.UPDATE_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		response.getWriter().write(
				 "<script language=\"javascript\">\n" +
						" parent.dw.close();" + 
						 " var param = parent.document.createElement('input'); " +
						 " param.type = 'hidden'; " +
						 " param.name = 'id'; " +
						 " param.value = " + tmp.getEmpNumber() +  ";" +
						 " parent.document.forms[0].appendChild(param);" +
						" parent.document.forms[0].submit(); \n" +
				 "</script>");
		return null;
	}

	private void initFormBean (EmpEducationUpdateForm beanForm) {

		beanForm.setAllLevels(ComboBoxInit.getAllEducations(false));
		beanForm.setAllMajors(ComboBoxInit.getAllMajors(false));
	}
	
	private String validateForm (EmpEducationUpdateForm beanForm) {
		
		if (beanForm.getInstitute() == null || "".equals(CommonUtils.normalizeString(beanForm.getInstitute()))) {
			return "Institute name cannot be empty!";
		}

		try {

			Short year = Short.parseShort(beanForm.getYear());
			if (year <= 0) {
				return "Year must be a positive integer!";
			}
			
			if (year > 80) {
				return "Year must not exceed 80.";
			}
		} catch (Exception e) {
			return "Year must be a positive integer and not exceed 80.";
		}
		
		Date startDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getStartDate()));
		Date endDate = CommonUtils.stringToDate(CommonUtils.normalizeString(beanForm.getEndDate()));

		if (endDate != null) {
			
			if (startDate == null) {
				return "Start date cannot be empty when end date is available!";
			}

			if (!endDate.after(startDate)) {
				return "End date must be after start date!";
			}
		}
		
		if (CommonUtils.checkLaterThanToday(beanForm.getStartDate(), -1, -1, -1)) {
			return "Start date must not be in the future!";
		}

		return StringConstants.BLANK;
	}
}
